import 'dart:io';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/app_permission/auth_tab.dart';
import 'package:yt_devops/components/app_permission/yt_tab_view_model.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/list_empty_widget.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/pages/alarm/alarm_home/alarm_list/alarm_list_item_view.dart';
import 'package:yt_devops/pages/alarm/alarm_home/widgets/alarm_chart.dart';
import 'package:yt_devops/pages/alarm/alarm_home/widgets/alarm_title.dart';
import 'package:yt_devops/pages/site/site_controller.dart';
import 'package:yt_devops/pages/site/site_observer_list/views/my_top_tabbar.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';
import 'alarm_home_controller.dart';

class AlarmHomePage extends GetView<AlarmHomeController> {
  /// 带路由+id的tag,用于区分页面
  final String? tagName;

  /// 站点id
  final int? siteId;

  /// 站点名称
  final String? siteName;

  /// 设备id
  final int? deviceId;

  /// 设备名称
  final String? deviceName;

  /// 什么类型的告警页
  final AlarmPageType? alarmPageType;

  AlarmHomePage({
    this.tagName,
    this.siteId,
    this.siteName,
    this.deviceId,
    this.deviceName,
    this.alarmPageType,
    Key? key,
  }) : super(key: key);

  @override
  AlarmHomeController get controller =>
      Get.put(AlarmHomeController(), tag: tagName);

  final siteHomeController = Get.put(SiteHomeController());
  Widget _generateSearchInput(context) {
    return Visibility(
      // visible: isTabPage != null && isTabPage!,
      child: DecoratedBox(
        decoration: const BoxDecoration(color: Colour.white),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Container(
                height: 54.h,
                margin: EdgeInsets.only(left: 16.w),
                child: BrnSearchText(
                  maxHeight: 54.h,
                  innerColor: Colour.backgroundColor,
                  hintText: ResKey.searchDeviceHint.tr,
                  innerPadding: EdgeInsets.fromLTRB(0, 8.h, 0, 8.h),
                  hintStyle: TextStyles.lf16,
                  textStyle: TextStyles.f16,
                  textInputType: TextInputType.text,
                  focusNode: controller.searchSiteFocusNode,
                  searchController: controller.searchController,
                  controller: controller.textController,
                  outSideColor: Colors.transparent,
                  borderRadius: BorderRadius.all(
                    Radius.circular(6.sp),
                  ),
                  onTextCommit: (content) =>
                      controller.getSearchSiteName(content),
                  onTextClear: () {
                    controller.getSearchSiteName("");
                    return false;
                  },
                ),
              ),
            ),
            // Gaps.hGap16,
            GestureDetector(
              onTap: () => controller.toFilter(context),
              child: Padding(
                padding: EdgeInsets.fromLTRB(20.w, 0, 16.w, 0),
                child: Image.asset(
                  ImageAssets.iconFilter,
                  width: 20.w,
                  height: 20,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _listBody() {
    Log.d('controller.alarmsList==' + controller.alarmsList.toString());
    if (controller.alarmsList == null) {
      return Container();
    } else if (controller.alarmsList!.isEmpty) {
      return ListEmptyWidget(topPosition: 82.h);
    } else {
      if (controller.alarmsList != null && controller.alarmsList!.isNotEmpty) {
        return ListView.builder(
          padding: EdgeInsets.zero,
          physics: const AlwaysScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            var data = controller.alarmsList![index];
            if (data.name == 'AlarmChartWidget') {
              return AlarmChartWidget(
                // service: controller.getAlarmsNum,
                errorNum: controller.alarmNumState.errorNum,
                alarmNum: controller.alarmNumState.alarmNum,
                warnNum: controller.alarmNumState.warnNum,
                infoNum: controller.alarmNumState.infoNum,
                alarmSum: controller.state.alarmSum,
                alarmNumList: [
                  controller.alarmNumState.errorNum!,
                  controller.alarmNumState.alarmNum!,
                  controller.alarmNumState.warnNum!,
                  controller.alarmNumState.infoNum!,
                ],
                callBack: (int index) {
                  Log.d('index===' + index.toString());
                  if (index == 4) {
                    controller.reqParams.levels = [];
                  } else {
                    controller.reqParams.levels = [
                      AlarmStatusGradeType.values[index].value
                    ];
                  }
                  controller.reqParams.current = 1;
                  controller.loadList();
                },
              );
            } else {
              return AlarmListItemView(
                isHistory: controller.isHistoryAlarm == 1 ? true : false,
                model: data,
                onItemTaped: (model) => controller.goAlarmDetail(model),
              );
            }
          },
          itemCount: controller.alarmsList?.length ?? 0,
        );
      } else {
        return Container();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    controller.tabs = [ResKey.currentAlarm.tr, ResKey.historyAlarm.tr];

    return GetBuilder<AlarmHomeController>(
        tag: tagName,
        initState: (state) {
          controller.isTabPage = tagName == null;
          controller.pageName = (deviceName ?? siteName) ?? '';
          controller.getTabPermission(alarmPageType);
          if (deviceId != null) {
            controller.deviceId = deviceId!;
          }
          if (siteId != null) {
            controller.siteId = siteId!;
          }
          controller.initData();
        },
        builder: (_) {
          return Scaffold(
            appBar: controller.isTabPage == true
                ? null
                : AppBar(
                    title: SizedBox(width: 205.w, child: getTab()),
                    leading: GestureDetector(
                      onTap: () {
                        siteHomeController.onInit();
                        Get.back();
                      },
                      child: SizedBox(
                        height: 44.h,
                        child: Icon(
                          Platform.isAndroid
                              ? Icons.arrow_back
                              : Icons.arrow_back_ios,
                          color: Colour.black,
                        ),
                      ),
                    ),
                  ),
            body: Column(
              children: <Widget>[
                /// 搜索框
                GestureDetector(
                  onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
                  child: _generateSearchInput(context),
                ),

                Visibility(
                  visible: controller.isTabPage == true,
                  child: getTab(),
                ),

                Visibility(
                  visible: controller.isTabPage == true,
                  child: Gaps.vGap2,
                ),

                /// 告警数量图表
                AlarmChartWidget(
                  // service: controller.getAlarmsNum,
                  errorNum: controller.alarmNumState.errorNum,
                  alarmNum: controller.alarmNumState.alarmNum,
                  warnNum: controller.alarmNumState.warnNum,
                  infoNum: controller.alarmNumState.infoNum,
                  alarmSum: controller.state.alarmSum,
                  alarmNumList: [
                    controller.alarmNumState.errorNum!,
                    controller.alarmNumState.alarmNum!,
                    controller.alarmNumState.warnNum!,
                    controller.alarmNumState.infoNum!,
                  ],
                  callBack: (int index) {
                    Log.d('index===' + index.toString());
                    if (index == 4) {
                      controller.reqParams.levels = [];
                    } else {
                      controller.reqParams.levels = [
                        AlarmStatusGradeType.values[index].value
                      ];
                    }
                    controller.reqParams.current = 1;
                    controller.loadList();
                  },
                ),

                Gaps.vGap10,

                /// 告警列表
                Expanded(
                  child: SmartRefresher(
                    controller: controller.refreshController,
                    enablePullDown: true,
                    enablePullUp: true,
                    header: ListTips.classicHeader,
                    footer: ListTips.generateClassicFooter,
                    onLoading: () => controller.onLoad(),
                    onRefresh: () => controller.onRefresh(),
                    child: _listBody(),
                  ),
                ),
              ],
            ),
          );
        });
  }

  Widget getTab() {
    return AuthTab(
        tabList: [
          YtTabViewModel(
            permissionString: controller.tabPermissions[0],
            labelString: ResKey.currentAlarm.tr,
            imageString: '',
            permissionWidget: Gaps.empty,
          ),
          YtTabViewModel(
            permissionString: controller.tabPermissions[1],
            labelString: ResKey.historyAlarm.tr,
            imageString: '',
            permissionWidget: Gaps.empty,
          )
        ],
        build: (context, filtes, c) {
          controller.filterPermission = filtes;
          controller.tabController = c;
          controller.tabController?.addListener(
            () {
              if (c.index == c.animation!.value) {
                controller.onRefresh();
              }
            },
          );
          return MyTopTabBar(
            controller.tabController!,
            filtes.map((e) => e.labelString).toList(),
            isScrollable: false,
            tabAlignment: TabAlignment.fill,
            labelStyle: controller.isTabPage == true
                ? null
                : TextStyles.f18.mediumStyle,
            unselectedLabelStyle:
                controller.isTabPage == true ? null : TextStyles.lf16,
            indicator: controller.isTabPage == true
                ? null
                : const UnderlineTabIndicator(
                    borderSide: BorderSide(
                        width: 0, // 设置边界宽度为0，使其不可见
                        color: Colors.transparent),
                  ),
          );
        });
  }
}
